package com.tanhua.manager.service;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.Admin;
import com.tanhua.dubbo.api.db.AdminApi;
import com.tanhua.manager.exceptions.TanhuaException;
import com.tanhua.manager.interceptors.AdminHolder;
import com.tanhua.manager.utils.JwtUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminService {

    @Reference
    private AdminApi adminApi;

    @Autowired
    private StringRedisTemplate redisTemplate;


//    存储token的前缀
    private static final String CACHE_KEY_TOKEN_PREFIX="MANAGE_TOKEN_";
//  存储验证码的前缀
    private static final String CACHE_KEY_CAP_PREFIX = "MANAGE_CAP_";


    //根据登录token，获取用户对象
    public Admin findAdminByToken(String token) {
        String adminStr = redisTemplate.boundValueOps(CACHE_KEY_TOKEN_PREFIX+token).get();
        if(adminStr == null) {
            return null;
        }
        redisTemplate.boundValueOps(CACHE_KEY_TOKEN_PREFIX+token).set(adminStr,2, TimeUnit.HOURS);//续期
        return JSON.parseObject(adminStr,Admin.class);
    }


    /**
     * 从redis中删除token缓存
     */
    public void removeToken(String token){
        String redisTokenKey = CACHE_KEY_TOKEN_PREFIX + token;
        this.redisTemplate.delete(redisTokenKey);
    }

    public ResponseEntity verification(HttpServletResponse response,String uuid) throws Exception {

//        生成一个验证码图片 返回给浏览器
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(300, 80);
        lineCaptcha.write(response.getOutputStream());

//        把验证码图片中的内容存到redis中
        String code = lineCaptcha.getCode();// 验证码图片中的内容
        redisTemplate.boundValueOps(CACHE_KEY_CAP_PREFIX+uuid).set(code,10,TimeUnit.MINUTES);
        return ResponseEntity.ok(null);

    }

    public ResponseEntity login(String username, String password, String verificationCode, String uuid) {
//        1、判断用户名和密码不能为空
        if(StringUtils.isBlank(username)||StringUtils.isBlank(password)){
            throw new TanhuaException(500,"用户名或密码不能为空");
        }
//        2、判断验证码  是否失效   是否相等
        String code = redisTemplate.boundValueOps(CACHE_KEY_CAP_PREFIX + uuid).get();
        if(StringUtils.isBlank(code)){
            throw new TanhuaException(500,"验证码失效");
        }

        if(!StringUtils.equals(code,verificationCode)){
            throw new TanhuaException(500,"验证码错误");
        }

        Admin admin = adminApi.findByUsername(username);
        if(admin==null){
            throw new TanhuaException(500,"用户名错误");
        }

        //           3、根据username查询用户  再比对密码
//        页面上传过来的密码加密后在和数据库中的密码比较
        password = DigestUtils.md5Hex(password);

        if(!StringUtils.equals(admin.getPassword(),password)){
            throw new TanhuaException(500,"密码错误");
        }
//          4、如果密码正确 需要jwt生成token字符串
        String token = JwtUtils.createToken(username, admin.getId(), "class158");

//        {token:""}
        Map resultMap = new HashMap();
        resultMap.put("token",token);

//        当前登录人的token放入到redis中
        redisTemplate.boundValueOps(CACHE_KEY_TOKEN_PREFIX+token).set(JSON.toJSONString(admin),2,TimeUnit.HOURS);

        return ResponseEntity.ok(resultMap);

    }

    public ResponseEntity logout() {

        Admin admin = AdminHolder.getAdmin();
        String token = admin.getToken();
        redisTemplate.delete(CACHE_KEY_TOKEN_PREFIX+token);

        return ResponseEntity.ok(null);

    }
}